package com.wwh.controller;

import com.wwh.entity.Monster;
import com.wwh.service.MonsterService;
import com.wwh.wwhspringmvc.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Albert
 * @date 2024/9/5-16:11
 * @describe
 */
@Controller
public class MonsterController {
    @Autowired
    private MonsterService monsterService;

    @RequestMapping(value = "/monster/list")
    public void listMonster(HttpServletRequest req, HttpServletResponse resp) {
        resp.setContentType("text/html;charset=utf-8");
        List<Monster> monsters = monsterService.listMonster();
        StringBuilder content = new StringBuilder("<h1>妖怪列表信息</h1>");
        content.append("<table border='1px' width='500px' style='border-collapse:collapse'>");
        for (Monster monster : monsters) {
            content.append("<tr><td>" + monster.getName() + "</td><td>" + monster.getId() + "</td><td>" + monster.getAge() + "</td><td>" + monster.getSkill() + "</td></tr>");
        }
        content.append("</table>");
        try {
            resp.getWriter().write(content.toString());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @RequestMapping(value = "/monster/find")
    public void findMonster(HttpServletRequest req, HttpServletResponse resp, String name) {
        resp.setContentType("text/html;charset=utf-8");
        List<Monster> monsters = monsterService.findMonsterByName(name);
        StringBuilder content = new StringBuilder("<h1>妖怪列表信息</h1>");
        content.append("<table border='1px' width='500px' style='border-collapse:collapse'>");
        for (Monster monster : monsters) {
            content.append("<tr><td>" + monster.getName() + "</td><td>" + monster.getId() + "</td><td>" + monster.getAge() + "</td><td>" + monster.getSkill() + "</td></tr>");
        }
        content.append("</table>");
        try {
            resp.getWriter().write(content.toString());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @RequestMapping(value = "/monster/login")
    public String loginMonster(HttpServletRequest req, HttpServletResponse resp, String name) {
        boolean login = monsterService.login(name);
        System.out.println("登录名字：" + name);
        req.setAttribute("name", name);
        if (login) {
            //return"forward:/login_ok.jsp";
            return "/login_ok.jsp";
        } else {
            return "forward:/login_error.jsp";
        }
    }

    @RequestMapping(value = "/monster/list/json")
    @ResponseBody
    //返回json格式的数据
    public List<Monster> listMonsterByJson(HttpServletRequest req, HttpServletResponse resp) {
        List<Monster> monsters = monsterService.listMonster();
        return monsters;
    }
}
